<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {ChatDotRound, User, Warning} from "@element-plus/icons-vue";
import {useRoute} from 'vue-router'
import {getApply, getApprovalRecords, getStatusByApplyId} from "@/api/apply.js";
import router from "@/router/index.js";
import {formatDateFromArray, numberToStatus, statusToNumber} from "@/utiles/typeConverter.js";

const route = useRoute()
const applyId = ref('')
const apply = ref({})
const approvalRecords = ref([
  {
    approvalTime: '2024-01-15T10:30:00',
    approvalRole: '部门经理',
    approver: '张三',
    approvalType: 0, // 0: 预支付款
    passed: 1, // 1: 通过
    comment: '出差事由充分，预算合理，同意预支付款申请'
  },
  {
    approvalTime: '2024-01-15T14:20:00',
    approvalRole: '财务人员',
    approver: '李四',
    approvalType: 1, // 0: 预支付款
    passed: 1, // 1: 通过
    comment: '预支付款已审批，请按规定使用'
  },
  {
    approvalTime: '2024-01-20T09:15:00',
    approvalRole: '部门经理',
    approver: '张三',
    approvalType: 2, // 1: 报销
    passed: 0, // 0: 未通过
    comment: '部分发票不符合报销规定，请重新整理后提交'
  }
])

onMounted(() => {
  applyId.value = route.query.id
  getStatus()
  getRecords()
  getApplyById()

})

const getApplyById = async () => {
  const {data} = await getApply(applyId.value)
  apply.value = data.data
}

const getStatus = async () => {
  const {data} = await getStatusByApplyId(applyId.value)
  currentStatus.value = numberToStatus(data.data)
}
const getRecords = async () => {
  const {data} = await getApprovalRecords(applyId.value)
  console.log(data)
}
const editApply = () => {
  router.push({
    name: 'ApplySubmit',
    query: {
      id: applyId.value
    }
  })
}

// 当前状态
const currentStatus = ref('差旅申请审核中')

// 状态步骤定义
const statusSteps = reactive([
  {name: 'applyDraft', title: '差旅申请', description: '差旅申请草稿', status: 'wait'},
  {name: 'applyReview', title: '差旅审批', description: '差旅申请审核中', status: 'wait'},
  {name: 'prePayment', title: '预支付款', description: '预支付款审核中', status: 'wait'},
  {name: 'reimburseApply', title: '报销申请', description: '报销申请审核中', status: 'wait'},
  {name: 'reimbursePay', title: '报销支付', description: '报销支付审核中', status: 'wait'},
  {name: 'completed', title: '完成', description: '已完成', status: 'wait'}
])

// 状态到步骤的映射
const statusToStepMap = {
  '差旅申请草稿': {step: 0, status: 'process', description: '差旅申请草稿'},
  '差旅申请未通过': {step: 1, status: 'error', description: '差旅申请未通过'},
  '差旅申请审核中': {step: 1, status: 'process', description: '差旅申请审核中'},
  '预支付款审核中': {step: 2, status: 'process', description: '预支付款审核中'},
  '预支付款审核通过': {step: 2, status: 'success', description: '预支付款审核通过'},
  '报销申请未通过': {step: 3, status: 'error', description: '报销申请未通过'},
  '报销申请审核中': {step: 3, status: 'process', description: '报销申请审核中'},
  '报销支付审核中': {step: 4, status: 'process', description: '报销支付审核中'},
  '已完成': {step: 5, status: 'success', description: '已完成'}
}

// 计算当前激活的步骤
const activeStep = computed(() => {
  console.log("??" + currentStatus.value)
  return statusToStepMap[currentStatus.value]?.step || 0
})

// 计算当前处理状态
const getProcessStatus = computed(() => {
  const currentStepInfo = statusToStepMap[currentStatus.value]
  return currentStepInfo?.status
})

const statusTips = {
  '差旅申请草稿': '您的差旅申请已保存为草稿，请尽快提交审核。',
  '差旅申请未通过': '您的差旅申请未通过审核，请根据审核意见修改后重新提交。',
  '差旅申请审核中': '您的差旅申请正在审核中，请耐心等待。',
  '预支付款审核中': '您的预支付款申请正在审核中。',
  '预支付款审核通过': '您的预支付款已审核通过，请按计划出行。',
  '报销申请未通过': '您的报销申请未通过审核，请根据审核意见修改后重新提交。',
  '报销申请审核中': '您的报销申请正在审核中。',
  '报销支付审核中': '您的报销支付正在审核中。',
  '已完成': '您的差旅申请流程已完成。'
};

const statusTipClasses = {
  'draft': 'warning',
  'travel_rejected': 'error',
  'travel_reviewing': '',
  'prepay_review': '',
  'prepay_approved': 'success',
  'reimburse_rejected': 'error',
  'reimburse_review': '',
  'payment_review': '',
  'completed': 'success'
};

// 获取审核类型的中文描述
const getTypeText = (type) => {
  const typeMap = {
    0: '差旅申请',
    1: '预支付款',
    2: '报销申请',
    3: '报销支付'
  }
  return typeMap[type] || type
}

// 获取审核结果的中文描述和颜色
const getResultInfo = (result) => {
  if (result === 1) {
    return {text: '审核通过', color: '#67C23A'}
  } else {
    return {text: '审核驳回', color: '#F56C6C'}
  }
}

const getStatusTip = (status) => {
  return statusTips[status] || '状态信息获取中...';
};

// 获取提示样式类
const getTipClass = (status) => {
  return statusTipClasses[status] || '';
};


// 获取状态文本的CSS类
const getStatusClass = (status) => {
  const classMap = {
    '差旅申请草稿': 'status-draft',
    '差旅申请未通过': 'status-rejected',
    '差旅申请审核中': 'status-processing',
    '预支付款审核中': 'status-processing',
    '预支付款审核通过': 'status-approved',
    '报销申请未通过': 'status-rejected',
    '报销申请审核中': 'status-processing',
    '报销支付审核中': 'status-processing',
    '已完成': 'status-completed'
  }
  return classMap[status] || 'status-default'
}

const getStepDescription = (stepIndex) => {
  const stepInfo = statusToStepMap[currentStatus.value]
  if (!stepInfo) return '待处理'

  if (stepIndex < stepInfo.step) {
    return '已完成'
  } else if (stepIndex === stepInfo.step) {
    return stepInfo.description
  } else {
    return '待处理'
  }
}


// 计算是否显示编辑差旅申请按钮
const showEditTravelButton = computed(() => {
  const editStatuses = ['差旅申请草稿', '差旅申请未通过', '差旅申请审核中', '预支付款审核中'];
  return editStatuses.includes(currentStatus.value);
});

// 计算是否显示提交报销文件按钮
const showReimburseButton = computed(() => {
  const submitStatuses = ['预支付款审核通过', '报销申请未通过'];
  return submitStatuses.includes(currentStatus.value);
});

const formatTime = (timeString) => {
  if (!timeString) return ''

  try {
    const date = new Date(timeString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return timeString
  }
}


// 获取角色标签类型
const getRoleTagType = (role) => {
  const roleMap = {
    '部门经理': 'primary',
    '财务人员': 'success',
    '系统管理员': 'warning'
  }
  return roleMap[role] || 'info'
}

const showDetail = () => {
  router.push({
    name: 'ApplyDetail',
    query: {
      id: applyId.value
    }
  })
}

const showReimburseManage = () =>{
  router.push({
    name: 'ReimburseSubmit',
    query: {
      id: applyId.value
    }
  })
}
</script>

<template>
  <div class="main">
    <div class="breadcrumb-section">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ name: 'ApplyManage' }">差旅管理</el-breadcrumb-item>
        <el-breadcrumb-item>申请状态</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container">

      <div class="status">

        <div class="current-status">
          <h3>当前状态: <span class="status-text"
                              :class="getStatusClass(currentStatus)">{{ currentStatus }}</span></h3>
        </div>

        <div class="status-tip" :class="getTipClass(currentStatus)">
          <div class="tip-title">状态提示</div>
          <div class="tip-content">{{ getStatusTip(currentStatus) }}</div>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">申请单号：</span>
              <span class="info-value">{{ apply.applyId || '--' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{formatDateFromArray(apply.startTime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">结束时间：</span>
              <span class="info-value">{{ formatDateFromArray(apply.endTime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">目的地：</span>
              <span class="info-value">{{ apply.destination || '--' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">申请目的：</span>
              <span class="info-value">{{ apply.purpose || '--' }}</span>
            </div>
          </div>

        </div>


        <!-- 状态流转步骤 -->
        <el-steps
          :active="activeStep"
          align-center
          finish-status="success"
          class="status-steps"
          :process-status="getProcessStatus"
        >
          <el-step
            v-for="(step,index) in statusSteps"
            :key="step.name"
            :title="step.title"
            :description="getStepDescription(index)"

          />
        </el-steps>

        <div class="action-buttons">
          <div class="action-group">
            <!-- 编辑差旅申请按钮 -->
            <el-button
              type="primary"
              class="action-btn"
              v-if="showEditTravelButton"
              @click="editApply()"
            >
              编辑差旅申请
            </el-button>

            <!-- 管理报销数据按钮 -->
            <el-button
              type="info"
              class="action-btn"
              v-if="showReimburseButton"
              @click="showReimburseManage()"
            >
              管理报销数据
            </el-button>
            <el-button
              type="primary"
              class="action-btn"
              @click="showDetail()"
            >
              查看详情
            </el-button>
          </div>
        </div>

      </div>

      <div class="timeline">
        <div class="header">
          <h3>审核记录</h3>
          <p>差旅申请全流程审核记录</p>
        </div>

        <div v-if="statusToNumber(currentStatus)===2 || approvalRecords.length === 0 " class="empty-state">
          <el-empty description="暂无审核记录"/>
        </div>
        <div v-else>
          <el-timeline>
            <el-timeline-item
              v-for="record in approvalRecords"
              :key="record.id || record.approvalTime"
              :timestamp="formatTime(record.approvalTime)"
              placement="top"
            >
              <el-card shadow="none" class="audit-card">
                <div class="audit-header">
                  <div class="reviewer-info">
                    <div class="reviewer">
                      <el-icon>
                        <User/>
                      </el-icon>
                      <span>{{ record.approver }}</span>
                    </div>
                    <div class="role">
                      <el-tag size="small" :type="getRoleTagType(record.approvalRole)">
                        {{ record.approvalRole }}
                      </el-tag>
                    </div>
                  </div>
                  <div
                    class="result"
                    :style="{ color: getResultInfo(record.passed).color }"
                  >
                    {{ getTypeText(record.approvalType) }} {{ getResultInfo(record.passed).text }}
                  </div>
                </div>

                <div v-if="record.comment" class="comment">
                  <div class="comment-label">
                    <el-icon>
                      <ChatDotRound/>
                    </el-icon>
                    <span>审核意见：</span>
                  </div>
                  <div class="comment-content">{{ record.comment }}</div>
                </div>

                <div v-if="record.passed === 0" class="reject-info">
                  <el-icon>
                    <Warning/>
                  </el-icon>
                  <span>审核未通过</span>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>

      </div>
    </div>
  </div>
</template>

<style scoped>

.container {
  background: #fff;
  padding: 30px;
  margin-bottom: 30px;
  margin-top: 12px;
  border: 1px solid #dddcdc;

}

.status {
  margin-bottom: 40px;

  .current-status {
    text-align: center;
    margin-bottom: 30px;
  }

  .current-status h3 {
    margin: 0;
    color: #606266;
  }

  .status-text {
    font-weight: bold;
    padding: 4px 8px;
    border-radius: 4px;
  }

  .status-steps {
    margin: 40px 0;
  }

  .status-selector {
    text-align: center;
    margin-top: 30px;
  }

  .status-selector h4 {
    margin-bottom: 15px;
    color: #606266;
  }

  .status-explanation {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .status-explanation h3 {
    color: #303133;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }

  .status-tip {
    margin-top: 20px;
    padding: 15px;
    border-radius: 8px;
    background: #ecf5ff;

    .tip-title {
      font-weight: 600;
      margin-bottom: 8px;
      color: #303133;
    }

    .tip-content {
      color: #606266;
    }

    .status-tip.warning {
      background: #fdf6ec;
      border-left-color: #e6a23c;
    }

    .status-tip.success {
      background: #f0f9e8;
      border-left-color: #67c23a;
    }

    .status-tip.error {
      background: #fef0f0;
      border-left-color: #f56c6c;
    }

    .info-grid {
      margin-top: 20px;
      display: flex;
      flex-direction: column;
    }

    .info-item {
      display: flex;
      align-items: flex-start;
      min-height: 24px;
    }

    .info-label {
      color: #666;
      font-size: 14px;
      min-width: 80px;
      flex-shrink: 0;
    }

    .info-value {
      color: #333;
      font-size: 14px;
      font-weight: 500;
      word-break: break-all;
    }

  }
}

.timeline {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;

  .header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
  }

  .header h3 {
    margin: 0 0 8px 0;
    font-size: 18px;
    color: #303133;
  }

  .header p {
    margin: 0;
    font-size: 14px;
    color: #909399;
  }


  .audit-card {
    margin: 10px 0;
    border-radius: 8px;
  }

  .audit-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
  }

  .reviewer-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .reviewer {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 500;
    color: #303133;
  }

  .reviewer .el-icon {
    color: #409EFF;
  }

  .role {
    margin-left: 8px;
  }

  .result {
    font-weight: 600;
    font-size: 16px;
    margin-right: 60px;
  }

  .comment {
    margin-top: 12px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;

  }

  .comment-label {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 6px;
    font-size: 13px;
    color: #606266;
    font-weight: 500;
  }

  .comment-label .el-icon {
    color: #409EFF;
  }

  .comment-content {
    color: #303133;
    line-height: 1.5;
    font-size: 14px;
  }

  .reject-info {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-top: 10px;
    padding: 8px 12px;
    background-color: #fef0f0;
    border-radius: 4px;
    color: #f56c6c;
    font-size: 13px;
    font-weight: 500;
  }

  .reject-info .el-icon {
    font-size: 16px;
  }

  .empty-state {
    text-align: center;
    padding: 40px 0;
  }

  /* 时间线样式调整 */

  :deep(.el-timeline-item__timestamp) {
    color: #909399;
    font-size: 13px;
  }

  :deep(.el-timeline-item__node) {
    background-color: #409eff;
  }

  :deep(.el-timeline-item__tail) {
    border-left: 2px solid #e4e7ed;
  }
}
</style>
